package cc.booku.owlbox.ThanksDonating;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.Decrypt;
import cc.booku.owlbox.Statistics.EqdetailActivity;
import cc.booku.owlbox.Statistics.PieChartUtil;
import cc.booku.owlbox.Statistics.chartListAdapter;
import cc.booku.owlbox.Statistics.chart_list_class;
import cc.booku.owlbox.Statistics.chart_pies2_class;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TDChartActivity extends AppCompatActivity {

    private PieChart pieChart;
    private HashMap dataMap;
    private androidx.appcompat.widget.Toolbar Toolbar;
    private GridView chart_list;
    private List<chart_list_class> chart_list_classList = new ArrayList<chart_list_class>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tdchart);

        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));

        String ProfileStr = FileoOperations.readAssetsTxt(TDChartActivity.this, "TxtData/OwlReport");
        chart_list = (GridView) findViewById(R.id.chart_list);
        chart_list.setFocusable(false);
        LoadToolbar();
        try {

            //读取配置文件信息
            JSONObject obj = JSONObject.parseObject(ProfileStr);
            String result = obj.getString("捐赠列表");

            String ciphertext = obj.getString("地址密文");
            String res = Decrypt.RsaDecrypt(TDChartActivity.this, ciphertext);
            HttpResponsePie(res + result);
        } catch (Exception e) {

            Log.i("response===========>", "");
//异常处理
        }

        try {

            //读取配置文件信息
            JSONObject obj = JSONObject.parseObject(ProfileStr);
            String result = obj.getString("捐赠列表");

            String ciphertext = obj.getString("地址密文");
            String res = Decrypt.RsaDecrypt(TDChartActivity.this, ciphertext);
            HttpResponselist(res + result);
        } catch (Exception e) {

            Log.i("response===========>", "");
//异常处理
        }


    }

    private chartListAdapter mchartListAdapter;
    public chart_list_class clC;

    //报表
    public void HttpResponselist(String Surl_file) {

        chart_list_classList.clear();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request.Builder requestBuilder = new Request.Builder().url(Surl_file);
        //可以省略，默认是GET请求
        requestBuilder.method("GET", null);
        Request request = requestBuilder.build();
        Call mcall = mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("1111", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsoninfo = response.body().string();


                //String jsonstr3 = jsonstr2.replace("$$$在线播放$", "|");


                ByteArrayInputStream stream = new ByteArrayInputStream(jsoninfo.getBytes());
                StringBuffer stringBuffer = new StringBuffer();
                String str = null;
                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                //03.使用fastJson解析Json、
                List<chart_list_class> subc = JSON.parseArray(stringBuffer.toString(), chart_list_class.class);
                for (chart_list_class pp : subc) {
                    clC = new chart_list_class();
                    String count = pp.getCount();
                    String num = pp.getNum();
                    String statistics_devicebrand = pp.getStatistics_devicebrand();

                    //Log.d("ImageviewHolder", "显示图片url======" + vod_class);


                    clC.setNum(num);
                    clC.setStatistics_devicebrand(statistics_devicebrand);
                    clC.setCount(count + "元");
                    //pfilmclass.setParea(carea);
                    //将结果添加到对象集合中
                    chart_list_classList.add(clC);
                }


                Message msg = new Message();
                msg.what = 70;
                handler.sendMessage(msg);//用activity中的handler发送消息
            }
        });

    }


    private void HttpResponsePie(String url) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                // Log.i("response===========>",res);

                Message msg = new Message();
                msg.what = 40;
                Bundle bundle = new Bundle();
                bundle.putString("res", res);  //往Bundle中存放数据
                msg.setData(bundle);//mes利用Bundle传递数据
                handler.sendMessage(msg);//用activity中的handler发送消息

            }
        });

    }


    private void LoadToolbar() {
        //新页面接收数据


        Toolbar = (Toolbar) findViewById(R.id.toolbar);

        Toolbar.setTitle("猫头鹰APP捐赠者");

        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                finish();
            }
        });

    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {


                case 40:
                    String res = msg.getData().getString("res").trim();
                    List<chart_pies2_class> list = JSON.parseArray(res, chart_pies2_class.class);
                    dataMap = new HashMap();
                    for (int i = 0; i < list.size(); i++) {
                        int num = list.get(i).getNum();
                        String statistics_devicebrand = list.get(i).getStatistics_devicebrand();
                        int count = list.get(i).getCount();

                        Log.i("response===========>", statistics_devicebrand.toString() + count);
                        dataMap.put(statistics_devicebrand, count);

                    }

                    pieChart = (PieChart) findViewById(R.id.chart1);
                    PieChartUtil.getPitChart().setPieChart(pieChart, dataMap, "猫头鹰", true);

                    //点击事件
                    pieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
                        @Override
                        public void onValueSelected(Entry e, Highlight h) {
                            PieEntry pieEntry = (PieEntry) e;
                            pieChart.setCenterText(pieEntry.getLabel());
                        }

                        @Override
                        public void onNothingSelected() {

                        }
                    });

                    break;

                case 70:
                    clickData((ArrayList<chart_list_class>) chart_list_classList);

                    break;


            }
        }
    };


    public void clickData(ArrayList<chart_list_class> subClassList) {

        mchartListAdapter = new chartListAdapter(R.layout.chart_list_item, TDChartActivity.this, subClassList);


        chart_list.setAdapter(mchartListAdapter);
        chart_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // Toast.makeText(ChartActivity.this, "Click item" + i, Toast.LENGTH_SHORT).show();
                final TextView num = (TextView) view.findViewById(R.id.num);//名称
                final TextView count = (TextView) view.findViewById(R.id.count);//数量
                final TextView statistics_devicebrand = (TextView) view.findViewById(R.id.statistics_devicebrand);
                String num1 = num.getText().toString();
                String count1 = count.getText().toString();
                String statistics_devicebrand1 = statistics_devicebrand.getText().toString();


                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString("Device", statistics_devicebrand1);
                intent.putExtras(bundle);
                intent.setClass(TDChartActivity.this, EqdetailActivity.class);
                startActivity(intent);

            }
        });


    }

}
